class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        int sizea = nums.size();
        if (sizea < 3) return res;

        sort(nums.begin(), nums.end());

        for (int i = 0; i < sizea - 2; ++i) {
            // 跳过重复的数字
            if (i > 0 && nums[i] == nums[i - 1]) continue;

            int left = i + 1, right = sizea - 1;

            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];

                if (sum == 0) {
                    res.push_back({nums[i], nums[left], nums[right]});
                    // 跳过重复的数字
                    while (left < right && nums[left] == nums[left + 1]) ++left;
                    while (left < right && nums[right] == nums[right - 1]) --right;
                    ++left;
                    --right;
                } else if (sum < 0) {
                    ++left;
                } else {
                    --right;
                }
            }
        }

        return res;
    }
};
